package io.renren.modules.medical.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.MedicalException;
import io.renren.common.result.ResultCodeEnum;
import io.renren.common.utils.*;
import io.renren.modules.medical.dao.HealthGuidanceDao;
import io.renren.modules.medical.entity.*;
import io.renren.modules.medical.service.DoctorInfoService;
import io.renren.modules.medical.service.HealthGuidanceService;
import io.renren.modules.medical.service.IllSubService;
import io.renren.modules.medical.service.PatientInfoService;
import io.renren.modules.medical.vo.medicalVo.HealthGuidanceListVo;
import io.renren.modules.medical.vo.medicalVo.StatusVo;
import io.renren.modules.medical.vo.weixinVo.ApiGuidanceListVo;
import io.renren.modules.sys.service.SysUserRoleService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.metadata.IPage;

@RequiredArgsConstructor
@Service("healthGuidanceService")
public class HealthGuidanceServiceImpl extends ServiceImpl<HealthGuidanceDao, HealthGuidanceEntity> implements HealthGuidanceService {

    private final PatientInfoService patientInfoService;

    private final IllSubService illSubService;

    private final DoctorInfoService doctorInfoService;

    private final SysUserRoleService sysUserRoleService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<HealthGuidanceEntity> queryWrapper = new LambdaQueryWrapper<>();
        // 设置基础构造条件
        String key = (String)params.get("key");

        // 根据原有参数获取原有的HealthGuidanceEntity集合
        if (StringUtils.isNotEmpty(key) && StringUtils.isNumeric(key)){
            Long patientId = Long.valueOf(key);
            queryWrapper.eq(HealthGuidanceEntity::getPatientId, patientId);
        }else if (StringUtils.isNotEmpty(key)){
                List<Long> patientIds = patientInfoService.getIdsByName(key);
                queryWrapper.in(patientIds != null && patientIds.size() > 0,
                        HealthGuidanceEntity::getPatientId, patientIds);
        }

        // 判断当前用户是医生还是管理员或者审核
        List<Long> roles = DoctorInfoUtils.getRole(sysUserRoleService);

        if(!roles.contains(Constant.SysRole.ADMIN.getValue()) && !roles.contains(Constant.SysRole.AUDITOR.getValue())){
            if (roles.contains(Constant.SysRole.DOCTOR.getValue())){
                // 医生就只访问当前医生创建的
                DoctorInfoEntity doctorInfo = DoctorInfoUtils.getDoctorInfo(doctorInfoService);
                queryWrapper.eq(QueryPageBaseEntity::getDoctorId, doctorInfo.getId());
            }else {
                throw new MedicalException(HttpStatus.SC_FORBIDDEN, "用户无权访问健康教育列表");
            }
        }

        // 根据修改时间排序
        queryWrapper.orderByDesc(BaseEntity::getUpdateTime);
        IPage<HealthGuidanceEntity> page = this.page(
                new Query<HealthGuidanceEntity>().getPage(params),
                queryWrapper
        );

        // 封装集合作为页面返回值
        List<HealthGuidanceEntity> records = page.getRecords();
        List<HealthGuidanceListVo> healthGuidanceListVos = records.stream().map(
                // 调用方法将需要的属性封装进来
                item -> (HealthGuidanceListVo) QueryPageUtils.listToVos(new HealthGuidanceListVo(), item, patientInfoService, illSubService, doctorInfoService)
        ).collect(Collectors.toList());

        Page<HealthGuidanceListVo> guidanceVoPage = new Page<>();
        BeanUtils.copyProperties(page, guidanceVoPage);
        guidanceVoPage.setRecords(healthGuidanceListVos);
        return new PageUtils(guidanceVoPage);
    }

    @Override
    public void saveHealthGuidance(HealthGuidanceEntity healthGuidance) {
        DoctorInfoEntity doctorInfoEntity = DoctorInfoUtils.getDoctorInfo(doctorInfoService);
        healthGuidance.setDoctorId(doctorInfoEntity.getId());
        this.save(healthGuidance);
    }


    @Override
    public void updateStatus(StatusVo statusVo) {
        HealthGuidanceEntity healthGuidanceEntity = new HealthGuidanceEntity();
        BeanUtils.copyProperties(statusVo, healthGuidanceEntity);
        DoctorInfoEntity doctorInfo = DoctorInfoUtils.getDoctorInfo(doctorInfoService);
        if (statusVo.getStatus() == Constant.AuditStatus.REJECT.getValue() || statusVo.getStatus() == Constant.AuditStatus.USING.getValue()) {
            HealthGuidanceEntity guidanceEntity = this.getById(statusVo.getId());
            if (guidanceEntity.getStatus() == Constant.AuditStatus.STOPING.getValue()){
                throw new MedicalException(ResultCodeEnum.CANT_UPDATE_STATUS.getCode(), "无法审核停用中的健康教育");
            }
            // 如果是审核通过或不过的话就添加上审核id
            healthGuidanceEntity.setAuditorId(doctorInfo.getId());
        }
        this.updateById(healthGuidanceEntity);
    }

    /**
     * 获取到健康指导集合
     */
    // TODO 动态获取用户id
    @Override
    public List<ApiGuidanceListVo> getList() {
        // 获取到用户id
        Long patientInfoId = 1L;
        LambdaQueryWrapper<HealthGuidanceEntity> guidanceWrapper = new LambdaQueryWrapper<>();
        // 3、病人id
        guidanceWrapper.eq(QueryPageBaseEntity::getPatientId, patientInfoId);
        // 2、在使用中的健康指导 1
        guidanceWrapper.eq(HealthGuidanceEntity::getStatus, Constant.AuditStatus.USING.getValue());
        // 3、创建时间
        guidanceWrapper.orderByDesc(BaseEntity::getCreateTime);
        List<HealthGuidanceEntity> resultList = this.list(guidanceWrapper);
        if (resultList == null || resultList.size() <= 0){
            throw new MedicalException(ResultCodeEnum.NOT_FIND_ERROR.getCode(), "空对象异常");
        }

        return resultList.stream().map(item -> {
            ApiGuidanceListVo apiGuidanceVo = new ApiGuidanceListVo();
            BeanUtils.copyProperties(item, apiGuidanceVo);
            Long subId = item.getSubId();
            IllSubEntity subEntity = illSubService.getById(subId);
            Long doctorId = item.getDoctorId();
            DoctorInfoEntity doctorInfoEntity = doctorInfoService.getById(doctorId);
            if (subEntity == null || doctorInfoEntity == null) {
                throw new MedicalException(ResultCodeEnum.NOT_FIND_ERROR.getCode(), "空对象异常");
            }
            apiGuidanceVo.setDoctorName(doctorInfoEntity.getName());
            apiGuidanceVo.setSubTitle(subEntity.getTitle());
            return apiGuidanceVo;
        }).collect(Collectors.toList());
    }
}